import { useState, useEffect } from 'react';
import { Form, Notification, Transfer } from 'antd';
import { goBack, componentsMap } from '@/utils/util';
import API from '@/api';
import { connect, useDispatch, useModel } from 'umi';
import UploadList from '@/components/UploadList';
import moment from 'moment';
import { Button, Space } from 'antd';
import FileList from '@/components/FileLists';
const RecordComponent = ({ id, orgList, recordOptions, status }) => {
  const formList = [
    {
      label: '演练名称',
      name: 'drillName',
      type: 'input',
      rules: [
        {
          required: true,
          message: '请输入演练名称',
        },
      ],
    },
    {
      label: '演练单位',
      name: 'orgId',
      type: 'select',
      otherProps: {
        options: orgList,
      },
      rules: [
        {
          required: true,
          message: '请选择所属单位',
        },
      ],
    },
    {
      label: '演练类型',
      name: 'drillType',
      type: 'select',
      otherProps: {
        options: recordOptions,
      },
      rules: [
        {
          required: true,
          message: '请选择演练类型',
        },
      ],
    },
    {
      label: '年度',
      name: 'year',
      type: 'datepicker',
      otherProps: {
        picker: 'year',
      },
      rules: [
        {
          required: true,
          message: '请选择年度',
        },
      ],
    },
    {
      label: '演练时间',
      name: 'drillTime',
      type: 'datepicker',
      rules: [
        {
          required: true,
          message: '请选择演练时间',
        },
      ],
    },
    {
      label: '演练地点',
      name: 'drillPlace',
      type: 'input',
      rules: [
        {
          required: true,
          message: '请选择演练地点',
        },
      ],
    },
    {
      label: '提交人',
      name: 'creator',
      otherProps: {
        disabled: true,
      },
    },
    {
      label: '提交时间',
      name: 'date',
      otherProps: {
        disabled: true,
      },
    },
    {
      label: '备注说明',
      name: 'remarks',
      type: 'textarea',
      isBlock: true,
    },
    {
      label: '演练内容',
      name: 'drillContent',
      type: 'textarea',
      otherProps: {
        autoSize: { minRows: 6 },
      },
      isBlock: true,
    },
  ];
  const [form] = Form.useForm();
  const { initialState } = useModel('@@initialState');
  const { username, orgId } = initialState.info;
  const [fileList, setfileList] = useState([]);
  const dispatch = useDispatch();
  const initOrgList = () => {
    dispatch({
      type: 'dict/queryOrgList',
      payload: {
        orgId,
      },
    });
  };
  if (!orgList) {
    initOrgList();
  }
  if (!recordOptions) {
    dispatch({
      type: 'dict/queryRecordType',
    });
  }
  const uploadOptions = {
    fileTypes: [
      'application/doc',
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    ],
    maxSize: 50,
    maxNum: 3,
    accept: [
      '.doc,.docx.,.pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,',
    ],
    acceptMessage: 'word/pdf',
  };
  const initDetail = () => {
    API.showEdr({
      id,
    }).then((res) => {
      if (res?.t) {
        const {
          drillName,
          drillType,
          remarks,
          createUserName,
          createTime,
          drillContent,
          drillTime,
          orgId,
          drillPlace,
          emergencyDrillRecordFileList,
          year,
        } = res.t;
        setfileList(emergencyDrillRecordFileList);
        form.setFieldsValue({
          drillName,
          drillType,
          drillTime: drillTime && moment(drillTime),
          remarks,
          drillContent,
          drillPlace,
          orgId,
          creator: createUserName,
          year: moment(year),
          date: createTime.split(' ').shift(),
          emergencyDrillRecordFileList,
        });
      }
    });
  };
  useEffect(() => {
    if (id) {
      initDetail();
    } else {
      form.setFieldsValue({
        creator: username,
        date: moment().format('YYYY-MM-DD'),
      });
    }
  }, [id]);

  const saveFn = (state) => {
    form.validateFields().then(() => {
      const values = form.getFieldsValue(true);
      values.state = state;
      let request = API.addEdr;
      if (id) {
        values.id = id;
        request = API.modEdr;
      }
      const title = !id ? '新增' : '更新';
      request({
        ...values,
        year: values.year && values.year.format('YYYY'),
        drillTime: values.drillTime && values.drillTime.format('YYYY-MM-DD'),
      }).then((res) => {
        if (res) {
          Notification.success({
            message: title + '成功',
          });
          goBack();
        }
      });
    });
  };
  return (
    <div className="main-x readOnly-x">
      <Form form={form}>
        <div className="bgf">
          <div className="ant-form-inline form-x max-x">
            {formList.map((item) => {
              return (
                <Form.Item
                  key={item.name}
                  label={item.label}
                  name={item.name}
                  className={item.isBlock ? 'block' : ''}
                  rules={item.rules}
                >
                  {componentsMap(item.type, item.otherProps, status === '1')}
                </Form.Item>
              );
            })}
            {status === '1' ? (
              <Form.Item label="附件信息" className="block">
                {
                  <FileList
                    fileList={fileList}
                    downloadUrl="/emergencydrillrecord/download"
                  />
                }
              </Form.Item>
            ) : (
              <Form.Item
                label="附件信息"
                extra="支持word/pdf格式,单个大小在50M以内"
                name="emergencyDrillRecordFileList"
                className="block"
              >
                <UploadList
                  uploadUrl="/emergencydrillrecord/fileUpload"
                  downloadUrl="/emergencydrillrecord/download"
                  options={uploadOptions}
                  defaultFiles={fileList}
                ></UploadList>
              </Form.Item>
            )}
          </div>
        </div>

        <div className="footer-x max-x">
          {status !== '1' ? (
            <Space size={18}>
              <Button type="primary" onClick={saveFn.bind(null, 0)}>
                保存
              </Button>
              <Button type="primary" onClick={saveFn.bind(null, 1)}>
                提交
              </Button>
              <Button type="primary" className="cancel-btn" onClick={goBack}>
                返回
              </Button>
            </Space>
          ) : (
            <Button type="primary" className="cancel-btn" onClick={goBack}>
              返回
            </Button>
          )}
        </div>
      </Form>
    </div>
  );
};

export default connect(({ dict }) => ({
  recordOptions: dict.recordOptions,
  orgList: dict.orgList,
}))(RecordComponent);
